﻿using ProductSystem.BLL;
using ProductSystem.BLL.Common;
using ProductSystem.Model;
using Fundway.Common;
using Fundway.Common.Caching;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace ProductSystem.Web.Controllers
{
    public class HomeController : ManageControllerBase
    {
        //
        // GET: /Home/
        #region 登录页面
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(string UserAccount, string Password)
        {
            ViewData["UserAccount"] = UserAccount;
            ViewData["Password"] = Password;
            if (string.IsNullOrEmpty(UserAccount))
            {
                ViewData["errorMsg"] = "请输入用户账号";
                return View();
            }
            if (string.IsNullOrEmpty(Password))
            {
                ViewData["errorMsg"] = "请输入密码";
                return View();
            }
            using (EntitiesModel dbContext = new EntitiesModel())
            {
                List<System_User_Info> userList = dbContext.System_User_Infos.Where(u => u.Account == UserAccount && u.Status == 1).ToList();
                if (userList.Count == 0)
                {
                    ViewData["errorMsg"] = "用户账号不存在，请核对后重新输入";
                    return View();
                }
                System_User_Info user = dbContext.System_User_Infos.FirstOrDefault(m => m.Account == UserAccount && m.Status == 1 && m.Password == EncryptManager.EncryptTokenForPassword(Password));
                if (user != null && !string.IsNullOrEmpty(user.Account))
                {
                    System_User_Role userRole = dbContext.System_User_Roles.FirstOrDefault(o => o.User_ID == user.ID);
                    //用户信息
                    LoginUser currentLoginUser = new LoginUser();
                    currentLoginUser.UserId = user.ID;
                    currentLoginUser.Name = user.User_Name;
                    currentLoginUser.Account = user.Account;

                    currentLoginUser.LoginTime = DateTime.Now;
                    currentLoginUser.LoginIp = HttpContext.Request.UserHostAddress;
                    currentLoginUser.Password = EncryptManager.EncryptTokenForPassword(Password);

                    //保存用户登录信息
                    AppUserSession.Instance().SetCurrentUser(currentLoginUser);

                    string cacheKeyCode = "UserFunction-" + user.ID;
                    CacheRepository.Remove(cacheKeyCode);
                    //检查用户权限信息有没有放到缓存
                    if (CacheRepository.Get(cacheKeyCode, true) == null)
                    {
                        System_User_InfoBll.GetUserFuntion(user.ID);
                    }

                    LogHelper.Instance().WriteLogSql("用户登录!");

                    //新增用户登录日志
                    Login_Log log = new Login_Log();
                    log.UserAccount = user.Account;
                    log.UserId = user.ID.ToString();
                    log.Login_Time = DateTime.Now;
                    log.Status = 1;
                    log.Login_IP = HttpContext.Request.UserHostAddress;
                    dbContext.Add(log);

                    //修改用户信息（IP和最后一次登录时间）
                    System_User_Info u = dbContext.System_User_Infos.FirstOrDefault(o => o.ID == user.ID);
                    u.Login_IP = HttpContext.Request.UserHostAddress;
                    u.Login_Time = DateTime.Now;
                    u.Revised_By = user.User_Name;
                    u.Revised_Date = DateTime.Now;
                    dbContext.SaveChanges();

                    if (userRole != null)
                    {
                        currentLoginUser.RoleId = userRole.Role_ID.Value;
                        if (userRole.Role_ID.ToString() == ConfigurationManager.AppSettings["WeatherUserRoleId"])     //气象局会签用户
                        {
                            return RedirectToAction("PartMeetingIndex", "PartMeeting");
                        }
                    }
                    string urlhost = Request.ServerVariables["HTTP_HOST"];
                    var destinationUrl = "http://" + urlhost;
                    return Redirect(destinationUrl);
                    //return RedirectToAction("HomeIndex", "Home");
                }
                else
                {
                    ViewData["errorMsg"] = "用户账号和密码不匹配，请重新输入";
                    return View();
                }
            }
        }
        #endregion
        #region 出错页面
        /// <summary>
        /// 系统超时
        /// </summary>
        /// <returns></returns>
        public ActionResult Error()
        {
            return View();
        }

        /// <summary>
        /// 系统报错
        /// </summary>
        /// <returns></returns>
        public ActionResult OtherError()
        {
            string str = Request["str"];
            return View();
        }
        #endregion
        #region 退出
        /// <summary>
        ///  退出
        /// </summary>
        /// <returns></returns>
        public ActionResult LogOut()
        {
            LoginUser currentLoginUser = null;
            AppUserSession.Instance().SetCurrentUser(currentLoginUser);
            AppUserSession.Instance().SetReturnUrl(null);

            string urlhost = Request.ServerVariables["HTTP_HOST"];
            var destinationUrl = String.Format("http://{0}{1}", urlhost,
                                   TBConfig.Instance().ManageLoginUrl());
            return Redirect(destinationUrl);
        }
        #endregion
        #region 系统框架
        /// <summary>
        /// 系统框架
        /// </summary>
        /// <returns></returns>
        [ManageAuthorize]
        public ActionResult HomeIndex()
        {
            LoginUser currentLoginUser = AppUserSession.Instance().GetCurrentUser();
            ViewData.Model = currentLoginUser;
            List<System_Menu> menuList = System_MenuBll.GetUserFuntionList(currentLoginUser.UserId);
            ViewData["PMenu"] = menuList.Where(o => o.Parent_ID == 0).OrderBy(o => o.Menu_Order).ToList();
            ViewData["MenuStr"] = GetMenuTreeJson(0, 1).ToString();
            return View();
        }

        /// <summary>
        /// 功能菜单树
        /// </summary>
        /// <param name="menuId">开始节点</param>
        /// <param name="typeId">类型</param>
        /// <returns>json对象</returns>
        [ManageAuthorize]
        public string GetMenuTreeJson(int menuId, int typeId)
        {
            StringBuilder sb = new StringBuilder();
            LoginUser user = AppUserSession.Instance().GetCurrentUser();
            List<System_Menu> SystemFunctionlist = System_MenuBll.GetUserFuntionList(user.UserId);
            sb.Append("[");
            foreach (System_Menu model in SystemFunctionlist)
            {
                sb.Append("{");
                sb.AppendFormat("\"id\":\"{0}\",", model.ID);

                if (typeId == 1)
                {
                    sb.AppendFormat("\"pId\":\"{0}\",", model.Parent_ID);
                    string pUrl = string.Format("/{0}/{1}", model.Menu_Controller, model.Menu_Action);
                    sb.AppendFormat("\"pUrl\":\"{0}\",", pUrl);
                    sb.AppendFormat("\"typeId\":\"{0}\",", model.Menu_Type);
                }
                sb.AppendFormat("\"name\":\"{0}\"", model.Menu_Name);
                sb.Append("},");
            }
            if (sb.ToString().EndsWith(","))
            {
                sb.Remove(sb.Length - 1, 1);
            }
            sb.Append("]");

            return sb.ToString();
        }
        #endregion
        #region 首页
        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        [ManageAuthorize]
        public ActionResult DefaultPage()
        {
            List<Desk> deskList = Desk_Bll.GetAllList();
            ViewData["EmptyCount"] = deskList.Where(x => x.Status == (int)DeskStatusEnum.Empty).Count();
            ViewData["DiningCount"] = deskList.Where(x => x.Status == (int)DeskStatusEnum.Dining).Count();
            ViewData["BookedCount"] = deskList.Where(x => x.Status == (int)DeskStatusEnum.Booked).Count();
            ViewData.Model = deskList;
            return View();
        }
        #endregion
    }
}
